import { defineStore } from 'pinia'

import { login,getCurrUserInfo } from '@/api/loginApi'

function retrieveLocalToken() {
    // console.log('read token');
    return localStorage.getItem('token') || ''
}
function clearLocalToken() {
    return localStorage.clear('token')
}

export default defineStore('user',{
    state: () => {
        return {
            token: retrieveLocalToken(), // 当刷新页面时, 这个会加载一次
            userInfo: null
        }
    },
    getters: {

    },
    actions: {
        aa() {
            console.log('aa')
        },
        doLogin(data) {
            return new Promise((resolve, reject) => {
                login(data).then(res=>{
                    // console.log('login',res)
                    this.token = res // 同样先存入到pinia中
                    localStorage.setItem('token', res)
                    resolve(data)
                }).catch(err=>{
                    reject(err)
                })
            })
        },
        // 用户退出后,清空用户信息
        clearUserInfo() {
            this.token = null
            clearLocalToken()
            this.userInfo = null
        },
        getUserInfo() {
            return new Promise((resolve, reject) => {
                getCurrUserInfo().then(res=>{
                    this.userInfo = res
                    // console.log(res,'获取到用户信息');
                    resolve()
                })
            })
        }
    }
})
